// src/pages/home/widgets/updateUserChannel/index.tsx
import styles from "@pages/home/widgets/channel/styles/edit.module.less";
import GeekIcon from "@shared/geekIcon";
import { SlideRef } from "@shared/slide";
import React from "react";
import { useRequestUserChannelsQuery } from "@service/channel";
import { useState } from "react";
import classNames from "classnames";
import { useEffect } from "react";
import { useDeleteUserChannelMutation } from "@service/channel";
import toast from "react-hot-toast";
import Selected from "@pages/home/widgets/updateUserChannel/widgets/selected";
import Unselected from "@pages/home/widgets/updateUserChannel/widgets/unselected";
interface Props {
  slideRef: React.RefObject<SlideRef | null>;
}

export default function UpdateUserChannel({ slideRef }: Props) {
  const [editing, setEditing] = useState(false);
  // 获取用户频道列表
  // 如果本地缓存存在数据则直接从本地缓存中获取, 本地缓存中没有则和服务端进行同步
  const { selectedChannels } = useRequestUserChannelsQuery(undefined, {
    selectFromResult: ({ data }) => ({ selectedChannels: data?.data.channels }),
  });
  // 用于删除用户频道
  const [deleteUserChannel, { isSuccess }] = useDeleteUserChannelMutation();

  // 检测频道是否删除成功
  useEffect(() => {
    // 频道删除成功 给出用户提示
    if (isSuccess) toast.success("频道删除成功");
  }, [isSuccess]);

  // 检测频道数量是否剩余4个
  useEffect(() => {
    // 如果频道数量剩余4个, 取消编辑状态
    if (selectedChannels?.length === 4) setEditing(false);
  }, [selectedChannels]);
  // 如果没有数据
  if (typeof selectedChannels === "undefined") return null;
  // 用于控制频道是否处于可删除状态
  
  // 渲染用户频道列表
  return (
    <div className={styles.container}>
      <div className={styles.close}>
        <GeekIcon
          type={"iconbtn_channel_close"}
          onClick={() => slideRef.current?.close()}
        />
      </div>
      {/* 已选择 */}
      <Selected slideRef={slideRef} />
      <div className={styles.space}></div>
      {/* 未选择 */}
      <Unselected />
    </div>
  );
}